package cn.lyjuan.first.netty.demo._5_netty_heartbeat.client.handler;

import cn.lyjuan.first.netty._4_netty_serialize.cst.MessageConst;
import cn.lyjuan.first.netty._4_netty_serialize.msg.MyMessage;
import cn.lyjuan.first.netty.demo._5_netty_heartbeat.cst.HeartbeatConst;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ClientHeartHandler extends ChannelInboundHandlerAdapter
{
    private static MyMessage HEART_MSG = new MyMessage(HeartbeatConst.HEAD_HEART, "", MessageConst.FOOT);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
    {
        if (!IdleStateEvent.class.isInstance(evt))
        {
            super.userEventTriggered(ctx, evt);
            return;
        }

        // idle事件
        IdleState state = ((IdleStateEvent) evt).state();

        // 如果发生写空闲，则发送一个心跳包
        if (state == IdleState.WRITER_IDLE)
            ctx.writeAndFlush(HEART_MSG);
    }
}
